package logic

import (
	"commerci/moddel/cache"
	"commerci/moddel/mysql"
	"commerci/pkg"
	"context"
	"errors"

	"commerci/commercirpc/commercirpc"
	"commerci/commercirpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *commercirpc.RegisterRequest) (*commercirpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Tel).Result()
	if result != in.SendSms {
		return nil, errors.New("短信验证码错误，请重新输入")
	}

	results, _ := cache.Rdb.Get(l.ctx, "Captcha"+in.Tel).Result()
	if results != in.Captcha {
		return nil, errors.New("图片验证码错误，请重新输入")
	}

	user := mysql.User{
		Tel:      in.Tel,
		Password: pkg.MD5(in.Password),
	}

	err := user.Register(mysql.DB, in.Tel)
	if err != nil {
		return nil, err
	}

	if user.Password != pkg.MD5(in.Password) {
		return nil, errors.New("密码错误，请重新输入")
	}

	return &commercirpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
